package com.microblogforsim.fragment;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.lzy.okgo.OkGo;
import com.microblogforsim.R;
import com.microblogforsim.activity.PreviewImgActivity;
import com.microblogforsim.activity.Topics_detailActivity;
import com.microblogforsim.adapter.TextAdapter;
import com.microblogforsim.callback.JsonCallback;
import com.microblogforsim.model.LzyResponse;
import com.microblogforsim.model.Topics;
import com.microblogforsim.utils.ACache;
import com.microblogforsim.utils.Urls;
import com.scwang.smart.refresh.layout.api.RefreshFooter;
import com.scwang.smart.refresh.layout.api.RefreshHeader;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.constant.RefreshState;
import com.scwang.smart.refresh.layout.listener.OnMultiListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;


import androidx.annotation.RequiresApi;
import androidx.fragment.app.Fragment;


import java.util.ArrayList;

public class Fragment_Index extends Fragment {
    private String TAG = "fuck";
    private static final int GET = 1;
    private View view;
    private ListView lv_list;
    private RefreshLayout fragment_index_refresh;
    private TextAdapter adapter;
    private TextView tv_share;
    private  int page = 0;
    private  int total = 0;

    private ArrayList<Topics.DataBean> list = new ArrayList<>();
    private ACache maCache  ;
    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        public void handleMessage(Message message) {
            super.handleMessage(message);
            switch (message.what) {
                case GET:

                    break;
            }
        }
    };
    private Handler handler1 = new Handler() {
        @SuppressLint("HandlerLeak")
        @Override
        public void handleMessage(@NonNull Message msg) {
            switch (msg.what) {
                case 0x200:
                    Log.d(TAG, "handleMessage: " + TAG);
            }
        }
    };

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_index, container, false);
        init();
        maCache =   ACache.get(getContext());
        maCache.clear();
        Topics topics = new Topics();
        topics=   (Topics)  maCache.getAsObject("list");
       if(topics!=null){
           isCache(topics,0);
       }else {
           okgo();
       }


        return view;
    }

    private void getData() {
        new Thread() {
            @Override
            public void run() {
                super.run();

                try {
                    Topics topics = null;
                    okgo();
                    Message msg = Message.obtain();
                    msg.what = GET;
                    msg.obj = TAG;
                    handler.sendMessage(msg);
                    Log.d(TAG, TAG);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }


    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);

        if (!hidden) {
//            更新数据
        }
    }

    /**
     * 刷新布局的回调函数
     * @param status
     */
    private  void getState(String status){

         switch (status){
             case  "Refreshing":
                 okgo();
                 break;
             case  "Loading":
                 if(page>=0&&page<total)
                 {
                     page++;
                     getMoreTopics(page);
                 }else if(page==total)
                 {
                     getMoreTopics(total);
                 }else
                 {
                     okgo();
                 }

                 break;
             case "ReleaseToLoad":

                 break;
             case "PullUpToLoad":
                 break;
             case "None":

                 break;

         }

    }

    private void getMoreTopics(int page) {
        OkGo.<LzyResponse<Topics>>get(Urls.SERVER + "Topics/getAllMore")//
                .tag(this)//
                //.headers("header1", "headerValue1")//头部
                .params("page", page)//传参
                .execute(new JsonCallback<LzyResponse<Topics>>() {
                    @RequiresApi(api = Build.VERSION_CODES.N)
                    @Override
                    public void onSuccess(com.lzy.okgo.model.Response<LzyResponse<Topics>> response) {
                        isCache(response.body().data,1);
                        fragment_index_refresh.finishLoadMore();//结束加载
                        fragment_index_refresh.finishRefresh();//结束刷新

                    }

                    @Override
                    public void onError(com.lzy.okgo.model.Response<LzyResponse<Topics>> response){
                        // handleError(response);
                        Log.d("TAG", "err: " + response.body().data.toString());

                    }
                });
    }

    private  void initlist(){
        adapter.replayAll(list);
        lv_list.setAdapter(adapter);
        lv_list.setSelection(list.size()-10);
        fragment_index_refresh.setOnMultiListener(new OnMultiListener() {
           @Override
           public void onHeaderMoving(RefreshHeader header, boolean isDragging, float percent, int offset, int headerHeight, int maxDragHeight) {

           }

           @Override
           public void onHeaderReleased(RefreshHeader header, int headerHeight, int maxDragHeight) {

           }

           @Override
           public void onHeaderStartAnimator(RefreshHeader header, int headerHeight, int maxDragHeight) {

           }

           @Override
           public void onHeaderFinish(RefreshHeader header, boolean success) {

           }

           @Override
           public void onFooterMoving(RefreshFooter footer, boolean isDragging, float percent, int offset, int footerHeight, int maxDragHeight) {

           }

           @Override
           public void onFooterReleased(RefreshFooter footer, int footerHeight, int maxDragHeight) {

           }

           @Override
           public void onFooterStartAnimator(RefreshFooter footer, int footerHeight, int maxDragHeight) {

           }

           @Override
           public void onFooterFinish(RefreshFooter footer, boolean success) {

           }

           @Override
           public void onLoadMore(@NonNull RefreshLayout refreshLayout) {

           }

           @Override
           public void onRefresh(@NonNull RefreshLayout refreshLayout) {

           }

           @Override
           public void onStateChanged(@NonNull RefreshLayout refreshLayout, @NonNull RefreshState oldState, @NonNull RefreshState newState) {
               Log.d(TAG, "onStateChanged: "+newState.name());
               getState(newState.name());
           }
       });
        lv_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @SuppressLint("WrongConstant")
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
             Intent intent = new Intent(getContext(), Topics_detailActivity.class);
                Topics.DataBean dataBean = new Topics.DataBean();
                dataBean = list.get(position);
                maCache.put("topic",dataBean);
                Bundle bundle = new Bundle();
                bundle.putInt("pos",position);
                intent.putExtras(bundle);
                startActivity(intent);
            }
        });
    }

    private void isCache(Topics topics,int status){
        list.clear();
        Topics old =  (Topics) maCache.getAsObject("list");
         int i = 0;
         if(status==1&&old!=null&&old.getData().size()>0){
             old.getData().addAll(topics.getData());
//             while (i < topics.getData().size()) {
//                 old.getData().add(topics.getData().get(i));
//                 i++;
//             }

         }else if(status==0) {
              old = topics;

        }


        if(old.getData().size()>0){
            i = 0;
            while (i < old.getData().size()) {
                list.add(old.getData().get(i));
                i++;
            }
            total =topics.getLast_page();
            page = topics.getCurrent_page();
            maCache.put("list",old);
            initlist();
        }else {
            Toast.makeText(getContext(), "获取微博失败", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 发起网络请求获取json数据
     */
    private void okgo() {


        OkGo.<LzyResponse<Topics>>get(Urls.SERVER + "Topics/getAll")//
                .tag(this)//
                //.headers("header1", "headerValue1")//头部
               //.params("param1", "paramValue1")//传参
                .execute(new JsonCallback<LzyResponse<Topics>>() {
                    @RequiresApi(api = Build.VERSION_CODES.N)
                    @Override
                    public void onSuccess(com.lzy.okgo.model.Response<LzyResponse<Topics>> response) {
                        isCache(response.body().data,0);
                        fragment_index_refresh.finishLoadMore();//结束加载
                        fragment_index_refresh.finishRefresh();//结束刷新

                    }

                    @Override
                    public void onError(com.lzy.okgo.model.Response<LzyResponse<Topics>> response){
                        // handleError(response);

                    }
                });

    }

    private void init() {
        if (list == null) list = new ArrayList<>();
        adapter = new TextAdapter(getContext());
        lv_list = view.findViewById(R.id.index_list);
        fragment_index_refresh = view.findViewById(R.id.fragment_index_refreshLayout);

    }


}
